﻿using FileTransportSpace;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using VCommons;

namespace Thrift.Client
{
    /// <summary>
    /// 文件传输客户端
    /// </summary>
    public class FileTransportService
    {
        public readonly static object lockObj = new object();
        /// <summary>
        /// 缓存块大小
        /// </summary>
        const int BUFFER_BLOCK = 1024 * 1024 * 4;

        public static void UploadTaskTest(Thrift.Transport.TSocket socket, FileTransport.Client fileTransport, string fromPath, string toPath)
        {
            byte[] buffer = new byte[BUFFER_BLOCK];
            long filesize = new FileInfo(fromPath).Length;
            int readBytes = 0;
            int count = 0;
            long i = 0;

            var sync = fileTransport.IsSync(toPath + Path.GetFileName(fromPath), ClientKey);
            if (sync.IsSync)//是否要进行继传
            {
                i = sync.CurrentSeek; //从断点处开始上传
                #region 多线程上传
                new WorkOfTask(1, (id) =>
                {
                    while (i <= filesize)//当线程执行完后释放后，可以重复使用
                    {
                        using (FileStream fs = new FileStream(fromPath, FileMode.Open, FileAccess.Read))
                        {
                            count++;
                            fs.Position = i;
                            readBytes = fs.Read(buffer, 0, buffer.Length);
                            fileTransport.Upload(new DataSegment
                            {
                                CurrentBytes = readBytes,
                                CurrentSeek = fs.Position,
                                Data = buffer,
                                Filename = toPath + Path.GetFileName(fromPath),
                                FileSize = filesize,
                                OrderNumber = count,
                                ClientKey = ClientKey,
                            });
                            System.Console.WriteLine("当前发送了请求:{3}个,线程为{2},已经上传了{0},共{1}", buffer.Length, fs.Length, id, count);

                        }
                        i += BUFFER_BLOCK;

                        if (i >= filesize)
                            return true;
                        else
                            return false;
                    }

                    return false;
                }, () =>
                {
                    fileTransport.UpdateDataSync(new DataSync
                    {
                        FilePath = toPath + Path.GetFileName(fromPath),
                        IsSync = false,
                        CurrentSeek = 0,
                        ClientKey = ClientKey,
                        OccurTime = DateTime.Now.ToString(),
                    });

                    Console.WriteLine("任务队列已经执行完成！");

                    socket.Close();//文件上传成功后，再关闭socket链接
                }).Action();
                #endregion

            }
            else
            {
                Console.WriteLine("已经成功上传！");
            }

        }
        /// <summary>
        /// 非分块下载
        /// </summary>
        /// <param name="fileTransport"></param>
        /// <param name="fromPath"></param>
        /// <param name="toPath"></param>
        public static void DownLoadTest(Thrift.Transport.TSocket socket, FileTransport.Client fileTransport, string fromPath, string toPath)
        {
            long fileSize = fileTransport.GetFileSize(new DataSync
            {
                FilePath = fromPath
            });
            long i = 0;
            var sync = fileTransport.IsSync(fromPath, ClientKey);
            if (sync.IsSync)
            {
                i = sync.CurrentSeek;
                while (i <= fileSize)
                {
                    using (FileStream stream = new FileStream(toPath + Path.GetFileName(fromPath), FileMode.Append, FileAccess.Write))
                    {
                        var data = fileTransport.Download(new DataSegment { CurrentSeek = i, ClientKey = ClientKey, Filename = fromPath });
                        if (data != null)
                        {
                            stream.Write(data.Data, 0, data.CurrentBytes);
                            System.Console.WriteLine("已经下载了{0}", data.CurrentBytes);
                        }

                    }
                    i += BUFFER_BLOCK;
                }
                //下载完成
                fileTransport.UpdateDataSync(new DataSync
                {
                    FilePath = fromPath,
                    IsSync = false,
                    CurrentSeek = 0,
                    ClientKey = ClientKey,
                });
                System.Console.WriteLine("文件下载成功！");
                socket.Close();
            }
            else
            {
                System.Console.WriteLine("文件已经下载！");
            }
        }

        /// <summary>
        /// 产生客户端唯一标识
        /// </summary>
        static string ClientKey
        {
            get
            {
                return GetMACAddress();
            }
        }

        //获取本机MAC地址
        static string GetMACAddress()
        {
            string MoAddress = "";
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                    MoAddress = mo["MacAddress"].ToString();
                mo.Dispose();
            }
            return MoAddress;
        }
    }
}
